package com.fenghuajueli.module_user.activity.vip;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Observer;
import androidx.lifecycle.Transformations;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.fenghuajueli.libbasecoreui.baseswitch.SwitchKeyUtils;
import com.fenghuajueli.libbasecoreui.constants.AppConfigInfo;
import com.fenghuajueli.libbasecoreui.constants.EventBusConstants;
import com.fenghuajueli.libbasecoreui.constants.PrivacyConstantsUtils;
import com.fenghuajueli.libbasecoreui.constants.SwitchKeyConstants;
import com.fenghuajueli.libbasecoreui.data.entity.eventbus.EventEntity;
import com.fenghuajueli.libbasecoreui.data.entity.goods.GoodsEntity;
import com.fenghuajueli.libbasecoreui.ui.PrivacyWebActivity;
import com.fenghuajueli.libbasecoreui.upload.UploadUtils;
import com.fenghuajueli.libbasecoreui.user.UserInfoUtils;
import com.fenghuajueli.libbasecoreui.utils.CommonUtils;
import com.fenghuajueli.libbasecoreui.utils.CustomItemDecoration;
import com.fenghuajueli.libbasecoreui.utils.QuickClickUtils;
import com.fenghuajueli.libbasecoreui.utils.RouteUtils;
import com.fenghuajueli.libbasecoreui.viewmodel.BaseViewModel;
import com.fenghuajueli.libbasecoreui.viewmodel.data.OtherCodeData;
import com.fenghuajueli.module_user.R;
import com.fenghuajueli.module_user.activity.UserViewModelBaseActivity;
import com.fenghuajueli.module_user.adapter.VipDescAdapter;
import com.fenghuajueli.module_user.adapter.VipPriceAdapter;
import com.fenghuajueli.module_user.constants.PayConstant;
import com.fenghuajueli.module_user.databinding.ActivityOpenVipBinding;
import com.fenghuajueli.module_user.dialog.SubscribeDialog;
import com.fenghuajueli.module_user.model.UserViewModel;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

@Deprecated
public class OpenVipActivity extends UserViewModelBaseActivity implements View.OnClickListener {
    private List<GoodsEntity> goodsEntityList;
    private GoodsEntity currentGood;
    private VipPriceAdapter vipPriceAdapter;
    @Autowired(name = RouteUtils.PARAMETER_FUN_TYPE)
    int funType = 0;
    //来自于那个界面
    @Autowired(name = RouteUtils.PARAMETER_FROM)
    int parameterFrom = 0;

    ActivityOpenVipBinding binding;

    /**
     * 当前选择的支付渠道方式
     */
    private String payChannel = "-1";

    /**
     * 支付展示：
     * 1. 正常（微信、支付宝都显示）
     * 2. 微信（只显示微信支付）
     * 3. 支付宝（只显示支付宝）
     */
    private int payChannelType = 1;
    /**
     * 点击订阅商品时保存上个支付方式。
     * 例如：开始是普通商品选择了微信支付，点击了订阅商品，支付方式切换为支付宝，再点击普通商品时需要切回微信支付
     */
    private String prePayChannel = "";
    //勾选同意协议可选项
    private final boolean protocolShow = true;
    private boolean checkAgree = false;


    private final UserViewModel userViewModel = new UserViewModel();

    @Override
    public BaseViewModel setBaseViewModel() {
        return userViewModel;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityOpenVipBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        EventBus.getDefault().register(this);
        binding.btnBack.setOnClickListener(v -> onBackPressed());
        binding.btnBuyKnow.setOnClickListener(v -> PrivacyWebActivity.start(OpenVipActivity.this, PrivacyConstantsUtils.ProtocolType.BUY_PROTOCOL));
        registerObserver();
        initData();
        initVipDesc();
        if (userViewModel != null) {
            userViewModel.handlerZfbSubscribeResult(getIntent(), this, currentGood);
        }
        payChannelshow();
        initPrivacy();
    }

    private void initVipDesc() {
        ArrayList<Integer> functionList = new ArrayList<>();
        int img = getResources().getIdentifier("user_icon_function_01", "mipmap", getPackageName());

        if (img == 0) {
            binding.rclFunctions.setVisibility(View.GONE);
            binding.ivFunctionsTitle.setVisibility(View.GONE);
        } else {
            binding.rclFunctions.setVisibility(View.VISIBLE);
            binding.ivFunctionsTitle.setVisibility(View.VISIBLE);
        }

        for (int i = 0; i < 10; i++) {
            int imgResId = getResources().getIdentifier("user_icon_function_0" + (i + 1), "mipmap", getPackageName());
            if (imgResId == 0) {
                continue;
            }
            functionList.add(imgResId);
        }

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        binding.rclFunctions.setLayoutManager(linearLayoutManager);

        CustomItemDecoration customItemDecoration = new CustomItemDecoration(this, ConvertUtils.dp2px(22), ConvertUtils.dp2px(15));
        binding.rclFunctions.addItemDecoration(customItemDecoration);

        VipDescAdapter vipDescAdapter = new VipDescAdapter(functionList);
        binding.rclFunctions.setAdapter(vipDescAdapter);
    }


    private void initData() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        binding.rclGoods.setLayoutManager(linearLayoutManager);

        CustomItemDecoration customItemDecoration = new CustomItemDecoration(this, ConvertUtils.dp2px(2), ConvertUtils.dp2px(6));
        binding.rclGoods.addItemDecoration(customItemDecoration);

        goodsEntityList = new ArrayList<>();
        vipPriceAdapter = new VipPriceAdapter(this, goodsEntityList);
        vipPriceAdapter.setOnItemClick((position, data) -> {
            currentGood = data;
            initSubscribeText();
        });
        binding.rclGoods.setAdapter(vipPriceAdapter);
        //根据需求来决定是否获取订阅类商品
        userViewModel.getGoodsList(this);
        binding.btnAliPay.setOnClickListener(this);
        binding.btnWechatPay.setOnClickListener(this);
        binding.btnPay.setOnClickListener(this);
        btnPayWayChecked(AppConfigInfo.PAY_CHANNEL_WECHAT, false);
        checkWechatPayOpen();
        binding.checkView.setOnClickListener(this);
    }

    private void payChannelshow() {
        payChannelType = SwitchKeyUtils.getPayChannelType();
        LogUtils.d("payChannelType==========" + payChannelType);
        if (payChannelType == 1) {
            binding.btnAliPay.setVisibility(View.VISIBLE);
            binding.btnWechatPay.setVisibility(View.VISIBLE);
        } else if (payChannelType == 2) {
            btnPayWayChecked(AppConfigInfo.PAY_CHANNEL_WECHAT, false);
            binding.btnAliPay.setVisibility(View.GONE);
            binding.btnWechatPay.setVisibility(View.VISIBLE);
        } else if (payChannelType == 3) {
            btnPayWayChecked(AppConfigInfo.PAY_CHANNEL_ZFB, true);
            binding.btnAliPay.setVisibility(View.VISIBLE);
            binding.btnWechatPay.setVisibility(View.GONE);
        } else {
            binding.btnAliPay.setVisibility(View.VISIBLE);
            binding.btnWechatPay.setVisibility(View.VISIBLE);
        }
    }


    @Override
    public void onClick(View view) {
        if (QuickClickUtils.isFastClick()) {
            return;
        }
        if (currentGood == null) {
            return;
        } else if (view.getId() == R.id.checkView) {
            checkAgree = !checkAgree;
            binding.checkView.setSelected(checkAgree);
        }
        if (view.getId() == R.id.btnAliPay) {
            btnPayWayChecked(AppConfigInfo.PAY_CHANNEL_ZFB, true);
        } else if (view.getId() == R.id.btnWechatPay) {
            btnPayWayChecked(AppConfigInfo.PAY_CHANNEL_WECHAT, false);
        } else if (view.getId() == R.id.btnPay) {
            if (protocolShow && currentGood.getVip_type() > 100 && !checkAgree) {
                ToastUtils.showShort("请先阅读并勾选同意协议");
                return;
            }
            PayConstant.goPay = true;
            PayConstant.pay = 1;
            checkPay();
        }
    }

    private void btnPayWayChecked(String payChannel, boolean selectAipay) {
        this.payChannel = payChannel;
        binding.btnAliPay.setChecked(selectAipay);
        binding.btnWechatPay.setChecked(!selectAipay);
    }

    private void checkPay() {
        if (TextUtils.equals(payChannel, AppConfigInfo.PAY_CHANNEL_ZFB)) {
            if (!CommonUtils.checkAliPayInstalled(this)) {
                showToast("请先安装支付宝客户端！");
                return;
            }
        } else {
            if (!CommonUtils.isWeixinAvilible(this)) {
                showToast("请先安装微信客户端！");
                return;
            }
        }
        checkUserIsSubscribeActive();
    }

    private void checkWechatPayOpen() {
        if (SwitchKeyUtils.getWechatPayType() == SwitchKeyConstants.WECHAT_PAY_TYPE_H5) {
            binding.btnWechatPay.setVisibility(View.VISIBLE);
        } else {
            if (AppConfigInfo.WECHAT_APP_ID.startsWith("xxxx") || AppConfigInfo.WECHAT_APP_SECRET.startsWith("xxxx")
                    || TextUtils.isEmpty(AppConfigInfo.WECHAT_APP_ID) || TextUtils.isEmpty(AppConfigInfo.WECHAT_APP_SECRET)) {
                binding.btnWechatPay.setVisibility(View.INVISIBLE);
            } else {
                binding.btnWechatPay.setVisibility(View.VISIBLE);
            }
        }
        payChannelshow();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (userViewModel != null) {
            userViewModel.handlerZfbSubscribeResult(intent, this, currentGood);
        }
    }

    /**
     * 检测用户是否处于支付宝周期扣款签约中
     * 签约类商品，不管是微信下单还是支付宝下单都要先检查用户
     * 是否是订阅会员并且判断当前是否还在签约中，签约中不允许在购买其他会员
     */
    private void checkUserIsSubscribeActive() {
        if (UserInfoUtils.getInstance().isForeverVip()) {
            ToastUtils.showLong("您已是永久会员，无须再开通！");
        } else {
            if (userViewModel != null) {
                userViewModel.checkIsSubscribeZfbActive(this, currentGood, payChannel);
            }
        }
    }

    private void initSubscribeText() {
        if (currentGood.getVip_type() > 100) {
            prePayChannel = payChannel;
            binding.tvSubscribe.setVisibility(View.VISIBLE);
            binding.btnWechatPay.setVisibility(View.INVISIBLE);
            payChannel = AppConfigInfo.PAY_CHANNEL_ZFB;
            btnPayWayChecked(AppConfigInfo.PAY_CHANNEL_ZFB, true);
            if (protocolShow) {
                binding.llCheckView.setVisibility(View.VISIBLE);
            }
            binding.btnBuyKnow.setVisibility(View.GONE);
        } else {
            if (!TextUtils.isEmpty(prePayChannel)) {
                payChannel = prePayChannel;
                prePayChannel = "";
                btnPayWayChecked(payChannel, TextUtils.equals(payChannel, AppConfigInfo.PAY_CHANNEL_ZFB));
            }
            binding.tvSubscribe.setVisibility(View.INVISIBLE);
            binding.llCheckView.setVisibility(View.INVISIBLE);
            binding.btnBuyKnow.setVisibility(View.VISIBLE);
            checkWechatPayOpen();
            return;
        }

        SpannableStringBuilder builder = getSubscribeTextBuilder();
        binding.tvSubscribe.setText(builder);
        binding.tvSubscribe.setMovementMethod(LinkMovementMethod.getInstance());
        checkAgree = false;
        binding.checkView.setSelected(false);
    }

    @NonNull
    private SpannableStringBuilder getSubscribeTextBuilder() {
        String text = switch (currentGood.getVip_type()) {
            case 105 -> currentGood.getGoods_desc() + " 《订阅须知》";
            case 1011 -> "7天试用到期自动续费包年会员，可随时取消 《订阅须知》";
            default -> "到期自动续费：¥" + currentGood.getRenew_price() + "  可随时取消 《订阅须知》";
        };
        SpannableStringBuilder builder = new SpannableStringBuilder(text);
        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(ContextCompat.getColor(OpenVipActivity.this, R.color.vipCenterSubTextColor));
                //超链接形式的下划线，false 表示不显示下划线，true表示显示下划线,其实默认也是true，如果要下划线的话可以不设置
                ds.setUnderlineText(false);
            }

            @Override
            public void onClick(@NonNull View widget) {
                SubscribeDialog dialog = new SubscribeDialog(OpenVipActivity.this);
                dialog.show();
            }
        };
        builder.setSpan(clickableSpan, text.length() - 6, text.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        return builder;
    }

    private void initPrivacy() {
        String first = "同意 ";
        String second = "《会员服务协议》";
        String third = "《订阅协议》";
        SpannableString spannableString = new SpannableString(first + second + "和" + third);
        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(ContextCompat.getColor(OpenVipActivity.this, R.color.priviceTextColor));
                //超链接形式的下划线，false 表示不显示下划线，true表示显示下划线,其实默认也是true，如果要下划线的话可以不设置
                ds.setUnderlineText(false);
            }

            @Override
            public void onClick(@NonNull View widget) {
                PrivacyWebActivity.start(OpenVipActivity.this, PrivacyConstantsUtils.ProtocolType.BUY_PROTOCOL);
            }
        };
        spannableString.setSpan(clickableSpan, first.length(), first.length() + second.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        clickableSpan = new ClickableSpan() {
            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(ContextCompat.getColor(OpenVipActivity.this, R.color.priviceTextColor));
                ds.setUnderlineText(false);
            }

            @Override
            public void onClick(@NonNull View widget) {
                PrivacyWebActivity.start(OpenVipActivity.this, PrivacyConstantsUtils.ProtocolType.SUBSCRIBE_PROTOCOL);
            }
        };
        spannableString.setSpan(clickableSpan, first.length() + second.length() + 1, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        binding.tvPrivacy.setText(spannableString);
        binding.tvPrivacy.setHighlightColor(Color.TRANSPARENT);
        binding.tvPrivacy.setMovementMethod(LinkMovementMethod.getInstance());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void event(EventEntity eventBusEntity) {
        if (eventBusEntity.getCode() == EventBusConstants.PAY_ERROR) {
            hideLoadingDialog();
        }
        if (eventBusEntity.getCode() == EventBusConstants.PAY_SUCCESS) {
            //延迟一秒从后台获取信息
            handlerPaySuccess();
        }
        if (eventBusEntity.getCode() == EventBusConstants.LOGIN_SUCCESS) {
            //延迟一秒是否支付
            pay();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        hideLoadingDialog();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 注册相关的数据的监听事件
     */
    private void registerObserver() {
        userViewModel.goodsList.observe(this, new Observer<List<GoodsEntity>>() {
            @Override
            public void onChanged(List<GoodsEntity> data) {
                goodsEntityList = data;
                currentGood = goodsEntityList.get(0);
                initSubscribeText();
                if (vipPriceAdapter != null) {
                    vipPriceAdapter.refreshData(goodsEntityList);
                }
            }
        });


        userViewModel.otherStatusData.observe(this, otherCodeData -> {
            if (otherCodeData.getCode() == OtherCodeData.PAY_SUCCESS) {
                handlerPaySuccess();
            } else if (otherCodeData.getCode() == OtherCodeData.UPDATE_USER_INFO) {
                //更新用户信息
            }
        });


        userViewModel.signStatus.observe(this, signStatusEntity -> {
            //用户是否处于支付宝签约状态 需要做ui改变就设置监听
        });

        Transformations.distinctUntilChanged(userViewModel.payOrder).observe(this, isResume -> {
            //支付取消 | 支付宝支付时 避免重复获取订单信息
            if (isResume && Boolean.TRUE.equals(userViewModel.isH5pay.getValue())) {
                binding.btnPay.postDelayed(() -> {
                    userViewModel.checkOrderPayActive(this, userViewModel.h5OrderId.getValue());
                }, 1000);
            }
        });
    }

    private void handlerPaySuccess() {
        showLoadingDialog();
        binding.btnPay.postDelayed(() -> {
            userViewModel.updateUserInfo(OpenVipActivity.this, currentGood);
            UploadUtils.payAction(OpenVipActivity.this, getApplication(), currentGood.getGoods_price());
        }, 1000);
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (Boolean.TRUE.equals(userViewModel.isH5pay.getValue())) {
            userViewModel.payOrder.postValue(true);
        }
    }

    public void pay() {
        if (PayConstant.goPay) {
            if (PayConstant.pay == 1) {
                checkPay();
            }
        }
    }
}